/*
 * @lc app=leetcode.cn id=783 lang=javascript
 *
 * [783] 二叉搜索树节点最小距离
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */

var maxValue = function(root) {
  return root.right ? maxValue(root.right) : root.val;
}

var minValue = function(root) {
  return root.left ? minValue(root.left) : root.val;
}

var minDiffInBST = function (root) {
  if (!root) return Number.MAX_SAFE_INTEGER;
  let diffLeft = root.left ? root.val - maxValue(root.left) : Number.MAX_SAFE_INTEGER;
  let diffRight = root.right ? minValue(root.right) - root.val : Number.MAX_SAFE_INTEGER;
  return Math.min(diffLeft, diffRight, minDiffInBST(root.left), minDiffInBST(root.right))
};
// @lc code=end

